<?php
class Controller_Admin_Keyword extends Controller_Template {

	public function __construct($request,$response)
	{
		parent::__construct($request,$response);
		$this->template	= ('smarty:admin/search/keyword');
	}
	
	/**
	 * 界面展示
	 */
	public function action_index($keyword_type)
	{
		$current_city = $this->request->query('city');
			
		$keyword_name=$this->get_keyword_name($keyword_type);

		//获取开放城市数组,如果请求的参数没有城市id，则使用第一个城市id作为当前城市
		$arr_citys= City::opened();
		if(empty($current_city))
		{
			//获得第一个开放的城市id
			$default_city = current($arr_citys);
			$default_city['id'] && $current_city = $default_city['id'];
		} 
		
		//查找关键词
		$arr_keywords = Search_Keyword::get_search_keywords($keyword_type,$current_city);
		if(is_array($arr_keywords))
		{
			$str_keyword = implode(',',array_values($arr_keywords));
		}
		else
		{
			$str_keyword = '';
		}
		//获得单个关键词长度限制范围和关键词个数限制范围
		$limit_count_max= Kohana::config('keyword.limit.count.max',6);
		$limit_count_min= Kohana::config('keyword.limit.count.min',1);
		$limit_length_max= Kohana::config('keyword.limit.length.max',8);
		$limit_length_min= Kohana::config('keyword.limit.length.min',1);

		$this->template->set_filename('smarty:admin/search/keyword');
		$this->template->set('keyword_type_name',$keyword_type);
		$this->template->set('keyword_name',$keyword_name);
		$this->template->set('current_city',$current_city);
		$this->template->set('cities',$arr_citys);
		$this->template->set('str_keywords', $str_keyword);
		$this->template->set('limit_count_max', $limit_count_max); 
		$this->template->set('limit_count_min', $limit_count_min); 
		$this->template->set('limit_length_max', $limit_length_max); 
		$this->template->set('limit_length_min', $limit_length_min); 		
		$this->response->body($this->template->render());
	}
	
	/**
	 * 设置关键词信息
	 */
	public function action_set()
	{
		$city = $this->request->post('city');
		$keyword_type = $this->request->post('keyword_type');
		$keywords = $this->request->post('keywords');

		if( ! empty($keywords))
		{
			$arr_keywords = explode(',', $keywords);
			$result_add = Search_Keyword::add_search_keywords($keyword_type,$city,$arr_keywords);
		}
		
		$url='/keyword/index/'.$keyword_type.'?city='.$city;
		if($result_add)
		{	
			$url=$url.'&flag=1';
		}
		else 
		{				
			$url=$url.'&flag=2';
		}
		$this->request->redirect($url,302);
	}
	
	/**
	 * 根据输入的关键字类别获得的对应的类别名称
	 * @param  $keyword_type 关键字类别 
	 * @return string  
	 */
	private function get_keyword_name($keyword_type)
	{
		$keyword_name='';
		switch ($keyword_type) {
			case 'cuxiao':
				$keyword_name = '促销关键词';				
			break;
			case 'pingce':
				$keyword_name = '评测关键词';				
			break;
			case 'mall':
				$keyword_name = '装修网关键词';				
			break;			
			default:
				$keyword_name = '' ;
			break;
		}
		return $keyword_name;
	}
	
}
